/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufpe.cin.dmo4.middleware.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 *
 * @author Danilo
 */
public class ServerRequestHandlerImpl extends ServerRequestHandler {

    private ServerSocket socket;
    private final int portNumber;
    private volatile boolean running;

    public ServerRequestHandlerImpl(int portNumber) {
        this.portNumber = portNumber;
    }

    public ServerRequestHandlerImpl(int portNumber, ServerHandlerListener listener) {
        super(listener);
        this.portNumber = portNumber;
    }

    @Override
    public void startListen() {
//        running = true;
//        try {
//            System.out.println("Aguardando conexões...");
//            socket = new ServerSocket(portNumber);
//            
//            while (running) {
//                Socket clientSocket = socket.accept();
//                
//                System.out.println("Client conectou!");
//                
//                handleRequest(clientSocket);
//            }
//        } catch (IOException ex) {
//            ex.printStackTrace();
//        }

        try {
            running = true;

            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

            serverSocketChannel.socket().bind(new InetSocketAddress(portNumber));

            while (true) {
                SocketChannel socketChannel
                        = serverSocketChannel.accept();

                System.out.println("Client conectou!");

                handleRequest(socketChannel);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    @Override
    public void stopListen() {
        running = false;

        try {
            socket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

//    private void handleRequest(Socket clientSocket) {
//        ClientConnection conn = new ClientConnection(clientSocket, getListener());
//        Thread t = new Thread(conn);
//        t.start();
//    }

    private void handleRequest(SocketChannel clientSocket) {
        ClientConnection conn = new ClientConnection(clientSocket, getListener());
        Thread t = new Thread(conn);
        t.start();
    }

}
